package com.tao.net

import com.squareup.moshi.Moshi
import com.tao.BuildConfig
import com.tao.net.converter.MoshiConverterFactory
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit

private const val TIMEOUT_READ = 30   //In seconds
private const val CONTENT_TYPE = "Content-Type"
private const val CONTENT_TYPE_VALUE = "application/json;charset=utf-8"
private const val TIMEOUT_CONNECT = 30   //In seconds
private const val BASE_URL = "https://gank.io/api/v2/"

/**
 * 提供Retrofit实例
 */
class ServiceGenerator constructor(moshi: Moshi) {
    private val okHttpBuilder: OkHttpClient.Builder = OkHttpClient.Builder()
    private val retrofit: Retrofit


    // 向请求中添加header
    private var header = Interceptor { chain ->
        val original = chain.request()

        val request = original.newBuilder()
            .header(CONTENT_TYPE, CONTENT_TYPE_VALUE)
            .method(original.method, original.body)
            .build()

        chain.proceed(request)
    }

    // 获取log
    private val logger: HttpLoggingInterceptor
        get() {
            val loggingInterceptor = HttpLoggingInterceptor()
            if (BuildConfig.DEBUG) {
                loggingInterceptor.apply { level = HttpLoggingInterceptor.Level.BODY }
            }
            return loggingInterceptor
        }

    init {
        okHttpBuilder.addInterceptor(header)
//        okHttpBuilder.addInterceptor(logger)
        // 连接超时时间
        okHttpBuilder.connectTimeout(TIMEOUT_CONNECT.toLong(), TimeUnit.SECONDS)
        // 读取超时时间
        okHttpBuilder.readTimeout(TIMEOUT_READ.toLong(), TimeUnit.SECONDS)
        // okhttp实例
        val client = okHttpBuilder.build()
        // retrofit实例
        retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL).client(client)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .build()
    }

    /**
     * 创建service
     */
    fun <S> create(serviceClass: Class<S>): S {
        return retrofit.create(serviceClass)
    }
}